package com.zhihuishu.micro.course.openapi.app.impl.teacher;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import com.google.common.collect.Lists;
import com.zhihuishu.micro.course.dto.CourseSpeakerDto;
import com.zhihuishu.micro.course.log.LoggerCollectionEnum;
import com.zhihuishu.micro.course.log.LoggerTemplateUtil;
import com.zhihuishu.micro.course.openapi.app.dto.CourseSpeakerOpenDto;
import com.zhihuishu.micro.course.openapi.app.teacher.CourseSpeakerOpenService;
import com.zhihuishu.micro.course.service.CourseSpeakerService;
import com.zhihuishu.remote.RemoteException;
import com.zhihuishu.remote.RemoteResult;
import com.zhihuishu.toolkit.helper.BeanHelper;

@Service("courseSpeakerOpenServiceForTeacherApp")
public class CourseSpeakerOpenServiceImpl implements CourseSpeakerOpenService {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private CourseSpeakerService courseSpeakerService;// 教学团队service

    @Override
    public RemoteResult<Integer> saveCourseSpeaker(CourseSpeakerOpenDto courseSpeakerOpenDto, long courseId,
            long userId) {
        RemoteResult<Integer> remoteResult = new RemoteResult<Integer>();
        try {

            if (logger.isDebugEnabled()) {
                logger.debug("保存课程主讲人列表信息为{}", courseSpeakerOpenDto);
            }
            Assert.notNull(courseSpeakerOpenDto, "列表对象不能为空");
            Assert.notNull(courseSpeakerOpenDto.getCourseId(), "课程id不能为空");

            courseSpeakerOpenDto.setId(null);
            courseSpeakerOpenDto.setIsDelete(0);// 默认为删除
            // 如果orderNumber属性为空，则查询该课程的对应type的教学团队最大排序号，+1后赋值给当前带保存对象
            if (courseSpeakerOpenDto.getOrderNumber() == null) {
            	Integer maxOrderNumber = courseSpeakerService.getMaxOrderNumberByCourseIdAndUserType(courseId, courseSpeakerOpenDto.getUserType());
            	courseSpeakerOpenDto.setOrderNumber(maxOrderNumber+1);
            }
            CourseSpeakerDto courseSpeakerDtoParam = BeanHelper.transTo(courseSpeakerOpenDto,
                    CourseSpeakerDto.class);
            courseSpeakerDtoParam = courseSpeakerService.insert(courseSpeakerDtoParam);
            remoteResult.setResult(courseSpeakerDtoParam.getId());
            LoggerTemplateUtil.saveLogger(String.format("保存课程主讲人信息为%s", courseSpeakerDtoParam), userId,
                    LoggerCollectionEnum.courseSpeakerCollection, courseId);

        } catch (Exception e) {
            remoteResult.setExceptionStack(e);
            remoteResult.setSuccess(false);
        }
        return remoteResult;

    }

    @Override
    public RemoteResult<List<Integer>> saveList(List<CourseSpeakerOpenDto> courseSpeakerOpenDtos,
            long courseId, long userId) {
        RemoteResult<List<Integer>> remoteResult = new RemoteResult<List<Integer>>();
        List<Integer> integers = Lists.newArrayList();
        try {
            if (logger.isDebugEnabled()) {
                logger.debug("保存课程主讲人列表信息为{}", courseSpeakerOpenDtos);
            }
            Assert.notNull(courseSpeakerOpenDtos, "列表对象不能为空");
            // 如果orderNumber属性为空，则查询该课程的对应type的教学团队最大排序号，+1后赋值给当前待保存对象
            Integer maxOrderNumber = null;
            if (courseSpeakerOpenDtos !=null && courseSpeakerOpenDtos.size() > 0 && courseSpeakerOpenDtos.get(0).getOrderNumber() == null) {
            	maxOrderNumber = courseSpeakerService.getMaxOrderNumberByCourseIdAndUserType(courseId, courseSpeakerOpenDtos.get(0).getUserType());
            }
            for (CourseSpeakerOpenDto courseSpeakerOpenDto : courseSpeakerOpenDtos) {
                Assert.notNull(courseSpeakerOpenDto, "保存对象不能为空");
                Assert.notNull(courseSpeakerOpenDto.getCourseId(), "课程id不能为空");
                courseSpeakerOpenDto.setId(null);
                courseSpeakerOpenDto.setIsDelete(0);// 默认为删除
                if (maxOrderNumber != null) {
                	courseSpeakerOpenDto.setOrderNumber(maxOrderNumber+1);
                	maxOrderNumber++;
                }
            }
            for (CourseSpeakerOpenDto courseSpeakerOpenDto : courseSpeakerOpenDtos) {
                CourseSpeakerDto courseSpeakerDtoParam = BeanHelper.transTo(courseSpeakerOpenDto,
                        CourseSpeakerDto.class);
                courseSpeakerDtoParam = courseSpeakerService.insert(courseSpeakerDtoParam);
                integers.add(courseSpeakerDtoParam.getId());
            }
            LoggerTemplateUtil.saveLogger(String.format("保存课程主讲人ids为%s", integers), userId,
                    LoggerCollectionEnum.courseSpeakerCollection, courseId);
            remoteResult.setResult(integers);
        } catch (Exception e) {
            remoteResult.setExceptionStack(e);
            remoteResult.setSuccess(false);
            logger.error("保存课程主讲人信息信息出错,保存参数为{}", courseSpeakerOpenDtos, e);
        }
        return remoteResult;
    }

    // 更新操作
    @Override
    public RemoteResult<Void> update(CourseSpeakerOpenDto courseSpeakerOpenDto, long courseId, long userId)
            throws RemoteException {
        RemoteResult<Void> remoteResult = new RemoteResult<Void>();
        if (logger.isDebugEnabled()) {
            logger.debug("接收到参数信息为:{}", courseSpeakerOpenDto);
        }
        try {
            Assert.notNull(courseSpeakerOpenDto, "更新对象不能为空");
            Assert.notNull(courseSpeakerOpenDto.getId(), "主键不能为空");
            CourseSpeakerDto courseSpeaker = BeanHelper.transTo(courseSpeakerOpenDto, CourseSpeakerDto.class);
            if (logger.isDebugEnabled()) {
                logger.debug("转换后的参数信息为:{}", courseSpeaker);
            }
            courseSpeakerService.update(courseSpeaker);
            LoggerTemplateUtil.saveLogger(String.format("更新主讲人信息为%s", courseSpeakerOpenDto), userId,
                    LoggerCollectionEnum.courseSpeakerCollection, courseId);
        } catch (Exception e) {
            remoteResult.setExceptionStack(e);
            remoteResult.setSuccess(false);
            logger.error("更新主讲人错误,参数信息为{}", courseSpeakerOpenDto, e);
        }
        return remoteResult;

    }

    // 查询
    @Override
    public RemoteResult<List<CourseSpeakerOpenDto>> courseSpeakearList(long courseId) throws RemoteException {
        RemoteResult<List<CourseSpeakerOpenDto>> result = new RemoteResult<List<CourseSpeakerOpenDto>>();
        try {
            List<CourseSpeakerDto> courseSpeakerList = courseSpeakerService.searchCourseSpeakerList(courseId);
            List<CourseSpeakerOpenDto> courseSpeakerOpenList = new ArrayList<CourseSpeakerOpenDto>();
            if (!CollectionUtils.isEmpty(courseSpeakerList)) {
                for (CourseSpeakerDto course : courseSpeakerList) {
                    CourseSpeakerOpenDto courseSpeakerOpenDto = BeanHelper.transTo(course,
                            CourseSpeakerOpenDto.class);
                    courseSpeakerOpenList.add(courseSpeakerOpenDto);
                }
            }
            result.setResult(courseSpeakerOpenList);
            result.setSuccess(true);
        } catch (Exception e) {
            throw new RemoteException(e).setMessage("查询教师团队的信息出错!");
        }
        return result;
    }

    @Override
    public RemoteResult<Void> deleteByIds(List<Integer> ids, long courseId, long userId) {
        RemoteResult<Void> remoteResult = new RemoteResult<Void>();
        try {
            Assert.notNull("ids", "删除列表不能为空");
            for (Integer integer : ids) {
                Assert.notNull(integer, "删除id不能为null");
            }
            for (Integer integer : ids) {
                courseSpeakerService.delete(integer);
            }
            LoggerTemplateUtil.saveLogger(String.format("删除教学团队%s", ids), userId,
                    LoggerCollectionEnum.courseSpeakerCollection, courseId);
        } catch (Exception e) {
            remoteResult.setExceptionStack(e);
            remoteResult.setSuccess(false);
            logger.error("删除教学团队列表信息出错,参数为{}", ids, e);
        }
        return remoteResult;
    }

    @Override
    public RemoteResult<Void> deleteById(int id, long courseId, long userId) {
        RemoteResult<Void> remoteResult = new RemoteResult<Void>();
        try {

            courseSpeakerService.delete(id);

            LoggerTemplateUtil.saveLogger(String.format("删除教学团队%d", id), userId,
                    LoggerCollectionEnum.courseSpeakerCollection, courseId);
        } catch (Exception e) {
            remoteResult.setExceptionStack(e);
            remoteResult.setSuccess(false);
            logger.error("删除教学团队列表信息出错,参数为{}", id, e);
        }
        return remoteResult;
    }

}
